<template>
	<rh-wx class="h5-container" :style="{
		'background-color': pageConf.background
	}">
		<div class="hidden-view" id="hiddenView"></div>
		<template v-if="activeInfo.activityTypeId == 7">
			<zpcjActive :baseUserData="baseUserData" :invitUrl="invitUrl" @active-share="activeShare"/>
		</template>
		<template v-else>
			<template v-if="boo.showPage" v-for="(model, index) in pageList">
				<template v-if="model.typeId == 'DBANNER'">
					<h5Banner :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DPACKAGE'">
					<h5Package class="package-content" :style="{
						'background-color': pageConf.background
					}" :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DRECRD'">
					<h5Record :form-item="model" :page-conf="pageConf" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DGROUPPACKAGE'">
					<h5Group class="package-content" :style="{
						'background-color': pageConf.background
					}" :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DSHOP'">
					<h5Shop :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DNotes'">
					<h5Notes :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DSubmit'">
					<h5Submit :form-item="model" @get-share="getShare" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DShare'">
					<h5Share :form-item="model" @get-share="getShare" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DIMAGE'">
					<h5DImage :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DINPUT'">
					<h5DInput :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
				<template v-if="model.typeId == 'DPIC'">
					<h5DPic :form-item="model" :id="`postHtml${index + 1}`"/>
				</template>
			</template>
		</template>
		
		<view class="hidden-user-share">
			<view class="user-share-container" id="postHtmlUser">
				<view class="share-title">
					{{activeInfo.activityName}}
				</view>
				<view class="share-content flex-between">
					<view class="left-content flex-column">
						<view class="user-info flex-normal">
							<image class="user-head" :src="baseUserData.headPortrait" mode="scaleToFill"></image>
							<text class="user-name">{{baseUserData.userNickName}}</text>
						</view>
						<view class="info-desc">
							长按识别二维码可立即抢购
						</view>
					</view>
					<rh-qrcode size="150" :qrcode="invitUrl || '--'"></rh-qrcode>
				</view>
			</view>
		</view>  
		<uni-popup zIndex="100" ref="pickerView" type="bottom" style="z-index: 9999999;">
			<view class="popup-view submit-popup flex-column">
				<view class="popup-header">
					<view class="header-title flex-normal">
						<image class="header-logo" src="/static/image/a-logo.png"></image>
						<text class="header-txt">爱车多多</text>						
					</view>
					<view class="header-desc flex-normal">
						分享后请关注 <text class="desc-txt">爱车多多</text> 公众号查看余额
					</view>
				</view>
				<image class="share-img" :src="imgUrlShare" mode="aspectFit"></image>
				<view class="share-desc">
					长按图片保存到手机
				</view>
			</view>
		</uni-popup>
	</rh-wx>
</template>

<script>
import html2canvas from "html2canvas";
import {isWechat} from '@/script/wx-premission.js'
import { makeCover, getConfigInfo, getActiveInfo } from "@/api/hd/index.js"
import { getUserInfo } from "@/api/common/index.js"
import wechat from '@/script/wechat.js'
import wxSDK from 'jweixin-module'
import pagesJson from '@/pages.json'
import h5Banner from './appH5/banner.vue'
import h5Package from './appH5/package.vue'
import h5Record from './appH5/record.vue'
import h5Group from './appH5/group.vue'
import h5Shop from './appH5/shop.vue'
import h5Notes from './appH5/notes.vue'
import h5Submit from './appH5/submit.vue'
import h5Share from './appH5/share.vue'
import h5DImage from './appH5/d-image.vue'
import h5DInput from './appH5/d-input.vue'
import h5DPic from './appH5/d-pic.vue'
import zpcjActive from './zpcj-active.vue'
import {mapActions} from 'vuex'
export default {
	components:{
		h5Banner,
		h5Package,
		h5Record,
		h5Group,
		h5Shop,
		h5Notes,
		h5Submit,
		h5Share,
		h5DImage,
		h5DInput,
		h5DPic,
		zpcjActive
	},
	data(){
		return {
			isWechat: isWechat(),
			route: {},
			boo: {
				showPage: false
			},
      imgUrlShare: '',
			invitUrl: '',
			shareWidth: 0,
			baseUserData: {},
			pageList: [],
			pageConf: {},
			activeInfo: {}
		}
	},
	onLoad(e) {
		if(!this.isWechat) return
		this.route = e
		wxSDK.hideAllNonBaseMenuItem()
	},
	async mounted(e) {
		let _self = this
		if(!this.isWechat) return
		uni.getSystemInfo({
			success: (res) => {
				let { windowWidth } = res
				_self.shareWidth = windowWidth
			}
		})
		let isSuccess = await _self.showWxApp()
		await _self.getActiveInfo()
		_self.initPages()
		if(isSuccess){
			await _self.queryUserInfo()
			await makeCover(_self.route['a']).then(res => {
				_self.invitUrl = res['data']['url']
			})
		}
	},
	methods: {
		...mapActions(['setActivity', 'setH5Config', 'setNeedRegister']),		
		async queryUserInfo(){
			let _self = this, isSuccess = false
			await getUserInfo().then(res => {
				_self.setNeedRegister(false)
				let {headPortrait, userNickName, phone} = res.data
				_self.baseUserData = {headPortrait, userNickName, phone}
				_self.$set(_self.baseUserData, 'headPortrait', headPortrait)
				_self.$set(_self.baseUserData, 'userNickName', userNickName)
				isSuccess = true
			})
			return isSuccess
		},
		async getActiveInfo(){
			let _self = this, isSuccess = false, {a} = this.$route['query']
			if(!a) return isSuccess
			await getActiveInfo(a).then(res => {
				_self.activeInfo = res.data
				_self.setActivity(_self.activeInfo)
				let {id, startingTime, endTime,
					whetherToShare, activityStatus,
					activityTypeId, activityName} = res.data
				if(activityStatus != 1){
					_self.$$router.replace({name: 'hdFail'})
				}else{
					uni.setStorage({
						key: `icar-wxActive`,
						data: {...{a: id, startingTime, endTime, whetherToShare}}
					})
					isSuccess = true					
				}
				if(activityTypeId == 7){
					isSuccess = false
					uni.setNavigationBarTitle({
						title: activityName,
					})
				}
			})
			return isSuccess
		},
		async initPages(){
			let _self = this
			_self.boo.showPage = false
			getConfigInfo(_self.route['a']).then(res => {
				let {draw = [], background, backgroundImg, modelClass, modelName, pageDescribe, pageTitle} = res.data || {}
				_self.pageList = draw
				_self.pageConf = {
					background, backgroundImg, modelClass, modelName, pageDescribe, pageTitle
				}
				if (wechat?.isWechat()) {
					let shareData = {
						title: pageTitle, // 分享标题
						desc: pageDescribe, // 分享描述
						imgUrl: backgroundImg, // 封面图
					}
				}
				uni.setStorage({
					key: `icar-wxActive`,
					data: {..._self.route}
				})
				_self.setH5Config(_self.pageConf).then(r => {
					_self.boo.showPage = true
				})
				uni.setNavigationBarTitle({
					title: pageTitle,
				})
				// document.title = pageTitle
			})
		},
		activeShare(img){
			let _self = this
		  this.imgUrlShare = img
			this.$refs.pickerView.open()
		},
		makeCanvas(params){
		  let _self = this
		  return new Promise((resolve, reject) => {
		    html2canvas(params.domObj, {
		      allowTaint: true,
		      useCORS: true,
					scale: 2,
					dpi: 600,
		      width: params.clientWidth,
		      height: params.clientHeight,
		      scrollY: -18,
		      scrollX: -0,
		      onclone(doc) {}
		    }).then(canvas => {
		      /** 新Image对象，可以理解为DOM */
		      let image = new Image();
		      /** 解决跨域 Canvas 污染问题 */
		      image.setAttribute("crossOrigin", "anonymous");
		      let imgUrl = canvas.toDataURL("image/jpge");
		      // this.imgUrl1 = imgUrl1
		      resolve(imgUrl)
		    });
		  })
		},
		/** 将html元素转换成海报图片 */
		async getShare() {
			uni.showLoading({title: '加载中',mask: true});
		  const posterHtml1 = document.querySelector('#postHtml1') ?? document.querySelector('#hiddenView');
		  const posterHtml2 = document.querySelector('#postHtml2') ?? document.querySelector('#hiddenView');
		  const posterHtml3 = document.querySelector('#postHtml3') ?? document.querySelector('#hiddenView');
		  const postHtmlUser = document.querySelector('#postHtmlUser') ?? document.querySelector('#hiddenView');
		  const img1 = await this.makeCanvas({
		    domObj: posterHtml1, 
		    clientHeight: posterHtml1.clientHeight, 
		    clientWidth: posterHtml1.clientWidth, 
		    name: '1'
		  })
		  const img2 = await this.makeCanvas({
		    domObj: posterHtml2, 
		    clientHeight: posterHtml2.clientHeight, 
		    clientWidth: posterHtml2.clientWidth, 
		    name: '2'
		  })
		  const img3 = await this.makeCanvas({
		    domObj: posterHtml3, 
		    clientHeight: posterHtml3.clientHeight, 
		    clientWidth: posterHtml3.clientWidth, 
		    name: '3'
		  })
		  const imgUser = await this.makeCanvas({
		    domObj: postHtmlUser, 
		    clientHeight: postHtmlUser.clientHeight, 
		    clientWidth: postHtmlUser.clientWidth, 
		    name: '4'
		  })
		  const img = await this.composeImgs(
		    { url: img1, 
		      width: posterHtml1.clientWidth,
		      height: posterHtml1.clientHeight,
		    }, {
		      url: img2, 
		      width: posterHtml2.clientWidth,
		      height: posterHtml2.clientHeight,
		    }, {
		      url: img3, 
		      width: posterHtml3.clientWidth,
		      height: posterHtml3.clientHeight,
		    }, {
		      url: imgUser, 
		      width: postHtmlUser.clientWidth,
		      height: postHtmlUser.clientHeight,
		    })
		  this.imgUrlShare = img
			uni.hideLoading();
			this.$refs.pickerView.open()
			console.log(11111)
		},
		appDrawImage(canvas, context, img, positionArr, type){
			let _self = this
			return new Promise((resolve, reject) => {
				const myImage = new Image();
				myImage.src = img.url;
				myImage.crossOrigin = 'Anonymous';
				myImage.onload = () => {
				  context.drawImage(myImage, type || 0, positionArr[0], _self.shareWidth, img.height); // 设置坐标并绘制
					const base64 = canvas.toDataURL('image/png'); //获取base64的图片流
					resolve(base64); // 成功之后返回图片路径
				};
			})
		},
		// 合成图片
		composeImgs(img1, img2, img3, img4) {
		  return new Promise(async (resolve, reject) => {
		    // 1，先创建一个画布
		    let canvas = document.createElement('canvas');
		    //2，创建画笔
		    const context = canvas.getContext('2d');
		    //3，设置背景的宽高
		    canvas.width = img1.width;
		    canvas.height = img1.height + img2.height + img3.height + img4.height
				await this.appDrawImage(canvas, context, img1, [0])
				await this.appDrawImage(canvas, context, img2, [img1.height])
				await this.appDrawImage(canvas, context, img3, [img1.height + img2.height])
				const base64 = await this.appDrawImage(canvas, context, img4, [img1.height + img2.height + img3.height])
				resolve(base64)
		  });
		},
	}
}
</script>
<style lang="scss" scoped>
	@import url('./appH5/model-h5.scss');
	@mixin fontStyle($color, $size, $weight: 500) {
		color: $color;
		font-size: $size;
		font-weight: $weight;
	}
	.hidden-view{
		width: 100%;
		height: 0.1rpx;
	}
	.h5-container{
		min-height: 100vh;
		background-color: #f2f2f2;
		position: relative;
		padding: 0;
		// .package-content{
		// 	width: 60%;
		// 	margin: auto;
		// }
	}
	.hidden-user-share{
		height: 0;
		overflow: hidden;
		.user-share-container{
			padding: 30rpx 20rpx;
			background-color: #fff;
			.share-title{
				text-align: center;
				@include fontStyle(#3D3D3D, 32rpx);
			}
			.share-content{
				padding: 30rpx 100rpx 0;
				.left-content{
					.user-info{
						.user-head{
							height: 60rpx;
							width: 60rpx;
							border-radius: 6rpx;
						}
						.user-name{
							margin-left: 10rpx;
							@include fontStyle(#3D3D3D, 24rpx);
						}
					}
					.info-desc{
						margin-top: 10rpx;
						@include fontStyle(#3D3D3D, 24rpx);
					}
				}
			}
		}
	}
	.submit-popup{
		background-color: #fff;
		padding: 0 36rpx;
		border-radius: 16rpx 16rpx 0 0;
		.share-img{
			margin: auto;
			text-align: center;
		}
		.share-desc{
			margin: 30rpx 0;
			text-align: center;
			@include fontStyle(#3D3D3D, 24rpx);
		}
		.popup-header{
			padding: 20rpx 0;
			.header-logo{
				width: 48rpx;
				height: 48rpx;
			}
			.header-txt{
				margin-left: 20rpx;
				@include fontStyle(#3D3D3D, 28rpx);
			}
			.header-desc{
				margin-top: 20rpx;
				@include fontStyle(#999, 24rpx);
				.desc-txt{
					padding: 0 10rpx;
					@include fontStyle(#0003AA, 24rpx);
				}
			}
		}
	}
</style>
